package com.gofunbuy.app.member;

import java.io.IOException;
import java.util.HashMap;

import org.json.JSONException;

import com.gofunbuy.R;
import com.gofunbuy.TabMemberGroup;
import com.gofunbuy.app.home.HomeActivity;
import com.gofunbuy.http.HttpClientImpl;
import com.gofunbuy.util.GoFunBuyUtils;
import com.gofunbuy.util.GoFunBuyUtils.GoFunBuyInterface;
import com.gofunbuy.util.GoFunBuyUtils.LoginXML;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SubMemberLoginActivity extends Activity implements
		OnClickListener, GoFunBuyInterface {
	private TextView tvBack, tvToRegist, tvTitle;
	private EditText etEmail, etPwd;
	private LinearLayout linearLayoutLogin;
	private String mEmail, mPwd;
	private Context mContext;

	// private LoginXML mLoginResult = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.member_login_layout);
		mContext = this;
		initLayout();
	}

	private void initLayout() {
		tvTitle = (TextView) findViewById(R.id.topbar_title);
		tvTitle.setText(R.string.title_login);

		tvBack = (TextView) findViewById(R.id.topbar_back);
		tvBack.setOnClickListener(this);
		tvBack.setVisibility(View.INVISIBLE);
		tvToRegist = (TextView) findViewById(R.id.id_login_to_regist);
		tvToRegist.setOnClickListener(this);

		etEmail = (EditText) findViewById(R.id.login_email);
		etPwd = (EditText) findViewById(R.id.login_pwd);
		linearLayoutLogin = (LinearLayout) findViewById(R.id.id_member_login_regist);
		linearLayoutLogin.setOnClickListener(this);
		mEmail = GoFunBuyUtils.readUsernameFromFile(mContext);
		mPwd = GoFunBuyUtils.readPwdFromFile(mContext);
		if (mEmail != null)
			etEmail.setText(mEmail);
		if (mPwd != null)
			etPwd.setText(mPwd);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.topbar_back:
			startActivity(TabMemberActivity.class);
			break;
		case R.id.id_member_login_regist:
			if (validateNotEmpty()) {
				if (!GoFunBuyUtils.isNetworkConnected(mContext)) {
					mHandler.sendEmptyMessage(MSG_NETWORD_ERROR);
					return;
				}
				showProgressDialog();
				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						HashMap<String, String> params = new HashMap<String, String>();

						try {
							params.put(ProtocalStatics.USERNAME, mEmail);
							params.put(ProtocalStatics.PWD, mPwd);
							params.put(ProtocalStatics.SHOPCODE, "goinside");
							GoFunBuyUtils.mLoginResult = HttpClientImpl
									.getInstance(mContext).loginService(
											mHandler, params);
							if (GoFunBuyUtils.mLoginResult != null) {
								if (!GoFunBuyUtils.mLoginResult.id.equals("0")) {// 登陸成功
									GoFunBuyUtils.writeUsernameToFile(mContext,
											mEmail, mPwd);
									GoFunBuyUtils.mUserID = GoFunBuyUtils.mLoginResult.id;
									mHandler.sendMessage(mHandler
											.obtainMessage(MSG_LOGIN_STATE, 1,
													0));

								} else {
									mHandler.sendMessage(mHandler
											.obtainMessage(MSG_LOGIN_STATE, -1,
													0));
								}
							} else {
								mHandler.sendMessage(mHandler.obtainMessage(
										MSG_LOGIN_STATE, -1, 0));
							}
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}).start();

			}
			break;
		case R.id.id_login_to_regist:
			if (TabMemberGroup.group != null)
				startActivity(SubMemberRegistActivity.class);
			else {
				Intent it = new Intent(this, SubMemberRegistActivity.class);
				startActivity(it);
			}
			break;
		}
	}

	private void startActivity(Class<?> a) {
		// 要跳转的Activity
		// Log.v("名字", a.getSimpleName() + " " + a.getName());
		Intent intent = new Intent(SubMemberLoginActivity.this, a);
		// 把Activity转换成一个Window，然后转换成View
		Window w = TabMemberGroup.group.getLocalActivityManager()
				.startActivity(a.getSimpleName(), intent);
		View view = w.getDecorView();
		// 设置要跳转的Activity显示为本ActivityGroup的内容
		TabMemberGroup.group.setContentView(view);
	}

	private boolean validateNotEmpty() {
		mEmail = etEmail.getText().toString();
		mPwd = etPwd.getText().toString();
		if ((mEmail != null && !mEmail.equals(""))
				&& (mPwd != null && !mPwd.equals(""))) {
			return true;
		} else {
			Toast.makeText(mContext, R.string.email_pwd_null_error,
					Toast.LENGTH_SHORT).show();
			return false;
		}
	}

	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case MSG_NETWORD_ERROR:
				hideProgressDialog();
				Toast.makeText(mContext, R.string.network_error,
						Toast.LENGTH_SHORT).show();
				break;
			case MSG_LOGIN_STATE:
				hideProgressDialog();
				if (msg.arg1 == -1)
					Toast.makeText(mContext, R.string.login_fail,
							Toast.LENGTH_SHORT).show();
				else if (msg.arg1 == 1) {
					Intent it = new Intent(SubMemberLoginActivity.this,
							HomeActivity.class);
					startActivity(it);
					finish();
				}
				break;
			}
		}

	};
	private Dialog mpDialog;

	private void showProgressDialog() {
		View diaView = View
				.inflate(this, R.layout.progress_dialog_layout, null);

		TextView remind = ((TextView) diaView
				.findViewById(R.id.id_progress_dialog_text));
		remind.setText(R.string.logining);
		remind.setTextColor(Color.RED);
		mpDialog = new Dialog(this, R.style.processDialog);
		mpDialog.setContentView(diaView);
		mpDialog.show();
	}

	private void hideProgressDialog() {
		if (mpDialog != null && mpDialog.isShowing())
			mpDialog.cancel();
	}
}
